import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react"
import { baseUrl } from "@/app/consts"
import type {
  AnimalsResponse,
  AnimalResponse,
  BreedResponse,
  BreedsResponse,
  CharacterResponse,
  CharactersResponse,
  AnimalWitCharacterNCuratorNShelter,
} from "@/app/animals/interfaces"
import qs from "qs"
import type { DefaultItemApiResponse } from "@/app/interfaces"
import type { Option } from "@/shared/ui/fancyMultiSelect"

export const animalsApi = createApi({
  reducerPath: "animalsApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  tagTypes: ["Animals"],
  endpoints: builder => ({
    getAnimals: builder.query<
      AnimalResponse[],
      { breed: Option[]; character: Option[] }
    >({
      query(args) {
        const breedIds = args.breed.map(breed => breed.value)
        const characterIds = args.character.map(character => character.value)
        const search = qs.stringify(
          {
            populate: ["characterIds", "photos", "breed"],
            filters: {
              $and: [
                args.character.length
                  ? {
                      characterIds: {
                        id: characterIds,
                      },
                    }
                  : undefined,
                args.breed.length
                  ? {
                      breed: {
                        id: breedIds,
                      },
                    }
                  : undefined,
              ],
            },
          },
          {
            encodeValuesOnly: true, // prettify URL
          },
        )

        return {
          url: `/animals?${search}`,
          credentials: "include",
        }
      },
      transformResponse(data: AnimalsResponse) {
        return data.data
      },
    }),
    getBreeds: builder.query<BreedResponse[], null>({
      query() {
        return {
          url: `/breeds?pagination[limit]=-1&sort[0]=name:asc`,
          credentials: "include",
        }
      },
      transformResponse(data: BreedsResponse) {
        return data.data
      },
    }),
    getCharacters: builder.query<CharacterResponse[], null>({
      query() {
        return {
          url: `/characters?pagination[limit]=-1&sort[0]=name:asc`,
          credentials: "include",
        }
      },
      transformResponse(data: CharactersResponse) {
        return data.data
      },
    }),
    getAnimal: builder.query<
      DefaultItemApiResponse<AnimalWitCharacterNCuratorNShelter>,
      string
    >({
      query(id) {
        const search = qs.stringify(
          {
            populate: [
              "characterIds",
              "curator.avatar",
              "shelter.logo",
              "photos",
              "breed",
            ],
          },
          {
            encodeValuesOnly: true, // prettify URL
          },
        )
        return {
          url: `/animals/${id}?${search}`,
          credentials: "include",
        }
      },
      transformResponse(data: {
        data: DefaultItemApiResponse<AnimalWitCharacterNCuratorNShelter>
      }) {
        return data.data
      },
    }),
  }),
})

export const {
  useGetAnimalsQuery,
  useLazyGetAnimalsQuery,
  useGetBreedsQuery,
  useGetCharactersQuery,
  useGetAnimalQuery,
} = animalsApi
